package chances.webui.helper;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import chances.webui.taglibs.LookuperTag;

public abstract class LookupHelper {
	static Logger logger = LoggerFactory.getLogger(LookuperTag.class);

	/**
	 * Map转换
	 * 
	 * @param coll
	 *            数据集合
	 * @param key
	 *            key 的属性名称
	 * @param value
	 *            值的属性名称
	 * @return map
	 */
	public static Map<Object, Object> build(Collection<?> coll, String key, String value) {
		Assert.notNull(coll);
		LinkedHashMap<Object, Object> result = new LinkedHashMap<Object, Object>();
		for (Object object : coll) {
			String aKey;
			try {
				aKey = BeanUtils.getProperty(object, key);
				String aValue = BeanUtils.getProperty(object, value);
				result.put(aKey, aValue);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

		}
		return result;
	}

	/**
	 * Map转换
	 * 
	 * @param coll
	 *            数据集合
	 * @param key
	 *            key 的属性名称
	 * @return
	 */
	public static Map<Object, Object> build(Collection<?> coll, String key) {
		Assert.notNull(coll);
		LinkedHashMap<Object, Object> result = new LinkedHashMap<Object, Object>();
		for (Object object : coll) {
			String aKey;
			try {
				aKey = BeanUtils.getProperty(object, key);
				result.put(aKey, object);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

		}
		return result;
	}
}
